<?

if(!@$externalscript){
// Include the settings
	require_once $_SERVER['DOCUMENT_ROOT']."/../_lib/base/settings.php";
}


// FUNCTION // Connect to database 
function db_connect() {
   
   global $MYSQL_ERRNO, $MYSQL_ERROR;

   $link = mysql_connect(DBHOST, DBUSER, DBPASS);
   mysql_set_charset('utf8',$link);
   
   if(!$link){
      $MYSQL_ERRNO = 0;
      $MYSQL_ERROR = "Connection failed to the host ".DBHOST;
      return 0;
   }else if(!mysql_select_db(DBNAME)) {
      $MYSQL_ERRNO = mysql_errno();
      $MYSQL_ERROR = mysql_error();
      return 0;
   }else return $link;
   
}


// connect to the server
$link = db_connect() or (mysql_error());







// FUNCTION //  Display a HTML notification message 
function display_message($params){

	if(($params['message']) OR ($params['list'])){

		// Type of message
		switch($params['type']){
			case 'neg';
				$style_class = 'message_neg';
			break;
			case 'pos';
				$style_class = 'message_pos';
			break;
			default;
				$style_class = '';
			break;
		}
		
		// Build message
		if($params['message']){
	
			$message_title = "<p clas='message_title'>".$params['message']."</p>";
		
		}
		
		// Build list
		if($params['list']){
	
			$message_list = "<ul>";
	
			foreach($params['list'] as $value){
				$message_list .= "<li>".$value."</li>";
			}
	
			$message_list .= "</ul>";
		
		}
		
		// Message build
		$message_string = "<div class='message ".$style_class."'>";
		$message_string .= $message_title;
		$message_string .= $message_list;
		$message_string .= "</div>";
	
	}
	
	return $message_string;
	
}










// CALL BACK FUNCTION // add slashes to var
function array_addslashes($var){
	// Default magic qoutes is set to on!
	return(addslashes($var));
}


// CALL BACK FUNCTION // strip slashes from var
function array_stripslashes($var){
	return(stripslashes($var));
}

// CALL BACK FUNCTION // converts HTML entities
function array_htmlsafe($var){
	return(htmlentities($var, ENT_QUOTES));
}


// CALL BACK FUNCTION // trim white space from var
function array_trim($var){

	return(trim($var));
   
}

// CALL BACK FUNCTION // add a escape if there is a quote
function array_mysql_real_escape_string($var){

	return(mysql_real_escape_string($var));
   
}




// FUNCTION // Check box is selected
function checked($var,$val){

	if($var==$val) return ' checked="checked" ';

}

// FUNCTION // Option is selected
function selected($var,$val){

	if($var==$val) return 'selected="selected" ';

} 






// MYSQL TRANSACTION FUNCTIONS 
function transaction_begin(){
	mysql_query("BEGIN") or die ("Couldn't execute query -".mysql_error());
}

function transaction_commit(){
	mysql_query("COMMIT") or die ("Couldn't execute query -".mysql_error());
}

function transaction_rollback(){
	mysql_query("ROLLBACK") or die ("Couldn't execute query -".mysql_error());
}








// FUNCTION // Outputs the HTML to display a date input box
function date_output($start_date=null){


	
	$days = array();
	$days_filler = array();
	
		for($i='1'; $i <= '31'; $i++){
			
			if($i < 10){
				$h = "0".$i;
			}else{
				$h = $i;
			}
			$days_filler['value'] = $h;
			$days_filler['description'] = $i;
			array_push($days, $days_filler);
	
		}
	

	
	$months_year = array();
	$months_year_filler = array();
	
		for($j='0'; $j <= '11'; $j++){
		
			$k = (date('n')+$start_date) + $j;
			$next_year = 0;
			
			if($k > 12){
				$k = $k - 12;
				$next_year = 1;
			}

			$timestamp = mktime(0, 0, 0, $k, 1, (date('Y') + $next_year));
			$value =  date('m-Y', $timestamp);
			$description =  date('F Y', $timestamp);
			$description =  date('M Y', $timestamp);
			
			$months_year_filler['value'] = $value;
			$months_year_filler['description'] = $description;
			$months_year_filler['description_short'] = $description_short;
			array_push($months_year, $months_year_filler);
			
			$timestampo='';

		}

	

	$my_dates = array('days' => $days, 'months_year' => $months_year);
	
	return $my_dates;

}






// FUNCTION // Make SABS format dates legible
function display_sabs_date($sabs_date, $format = 'j M y'){

	// SABS format YYMMDD

	if(!$sabs_date || $sabs_date == '0000' || (strlen($sabs_date) != 6)){

		return "n/a";
		
	}else{
		
		$y = substr($sabs_date,0,2);
		$m = substr($sabs_date,2,2);
		$d = substr($sabs_date,4,2);
		
		$timestamp = mktime(0, 0, 0, $m, $d, $y);
		$display_date = date($format, $timestamp);
		
		return $display_date;
		
	}

}



// FUNCTION // validate email
function validate_email($email) {

	if (!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) { 
		return false;
	}else{
		return true;
	}

}


// FUNCTION // Check if date is valid ( FORMAT YYYY-MM-DD )
function date_validator($s_date){


	//check if dates are valid
	$a_date = explode('-', $s_date);
	
	$y = $a_date[0];
	$m = $a_date[1];
	$d = $a_date[2];
		
	return checkdate($m, $d, $y);

}







// FUNCTION // Trim a string by specified amount
function trim_me($string, $length, $suffix = "..."){

	
	if (strlen($string) > $length){
		$string = wordwrap($string, $length, "#@~");
		$string = substr($string, 0, strpos($string, "#@~"));
	}

	return $string.$suffix;

}



// FUNCTION // to round numbers 
function round_money($string){

	if(strstr($string,'.')){
		$string = strrev($string);
		$string = strstr($string, '.');
		$string = str_replace('.','',$string);
		$string = strrev($string);
	}
	
	return number_format($string);
	
}




// FUNCTION // checkbox is checked
function checked_from_array($var,$list){

	$my_array = explode(',' , $list);
	
	for($i = 0; $i < count($my_array); $i++){

		if($var==$my_array[$i]) return "checked";
	
	}

}








// FUNCTION // DISLPAY FILE SIZE IN MB
function display_file_size($size) {

	if($size<99999){
		return round($size/1000, 2)."KB";
	}else{
		return round($size/1000000, 2)."MB";
	}

}




// FUNCTION // Generate a unique id
function unique_id(){

   return md5(uniqid(time()));

}






// FUNCTION // trim values in array
function trim_array($array){


// USE FILTER / ARRAY_MAP CALL BACK FUNCTION ??????

	$count = count($array);
	
	for($i = 0;$i < $count; $i++){

		if(!$key == key($array[$i])){
			$key = $i;
		}
		$array[$key] = trim($array[$i]);

	}
	
	return $array;

}




// FUNCTION // Outputs the HTML to display a date input box 
function output_rating($rating, $type, $inline=false){

if(!empty($rating)){

	if($inline){
		$style = "padding-top: 2px";
	}else{
		$style = "line-height: 12px; display: block;";
	}
	
	switch ($type){
		case "rate";
			$img_src = "rate_".$rating.".png";
			$alt_type = " rating ";
		break;
		case "star";
			$img_src = "star_".$rating.".png";
			$alt_type = " rating ";
		break;
	}

		
	$output = "<span style='".$style."'>";
	$output .= "<img src='/images/".$img_src."' class='star_rating_image' alt='".$rating." ".$alt_type."' />";
	$output .= "</span>";
		
	return $output;
	
}

}





// FUNCTION // to remove zeros
function remove_zeros($var){
	$var = $var + 0;
	if($var !== "0.00" || $var !== "0"){
		return $var;
	}
}



// FUNCTION //  Removes duplicates from a Multi-demensional Array
function unique_md_array($input_array){

	$output_array = array();
	
	foreach($input_array as $value){
		if(!in_array($value, $output_array)){
			array_push($output_array, $value);
		}
	}

	return $output_array;

}






// FUNCTION // change HTML entities back to characters
function unhtmlentities($string){

    // replace numeric entities
    $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
    $string = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $string);
    // replace literal entities
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    return strtr($string, $trans_tbl);
	
}



	
// FUNCTION // make a string URL friendly
function make_string_url_friendly($string){

	// Example string: "My Destination (Ireland)"
	// Example output: "my_destinations"
	// Cahge to lowercase
	// Replace " " with "_"
	// Remove any characters that cannot be used in a URL. Example remove "'"
	// Remove the brackets and text between brackets
	
	// Convert any html entities to single characters
	$string = html_entity_decode($string, ENT_QUOTES, "ISO-8859-1");
	// charachters to search for
	$searchfor = array("/'/", "/ /", "/(\()(.*)(\))/","/&/","/__/");
	// charachters to replace with
	$replacewith = array("", "_", "", "","_");
	 // do replacement
	$string = preg_replace($searchfor, $replacewith, $string);
	// clean unwanted underlines at start or end of string
	$string = strtolower(trim($string, "_"));
	
	// return result
	return  $string;
	
}	





	
// FUNCTION // OPTIONAL DEFAULT VALUE
function default_value($value,$default){

	if(!$value){
		return $default;
	}else{
		return $value;
	}
	
}	


// FUNCTION // return an array in list format "value,value,value"

// refactoring advice: this can be replaced by implode(',', $my_array);
function array_2_string($my_array,$delimiter=','){

	if(is_array($my_array)){
	
		$array_count = count($my_array)-1;
		
		for($i=0;$i<=$array_count;$i++){
		
			$string .= $my_array[$i];
			if($i<$array_count) $string .= $delimiter;
	
		}

		return $string;
		
	}

}




// FUNCTION // Make SABS format dates into a timestamp
function sabs_date_2_time_stamp($date,$format=false){

	// SABS format YYMMDD
	// If the format is not sent then the timestamp is returned

	if(empty($date)){

		return false;
		
	}else{

		$y = substr($date,0,2);
		$m = substr($date,2,2);
		$d = substr($date,4,2);

		$timestamp = mktime(0, 0, 0, $m, $d, $y);
		
		if($format){
			$return_string = date($format, $timestamp);
		}else{
			$return_string = $timestamp;
		}
		
		return $return_string;
		
	}

}

// Display sabs formated flight times
function sabs_flight_time_2_std($time){

	if(!empty($time)){
	
		return substr($time,0,2).":".substr($time,2,2);
	
	}

}


// add zeros to a string within an array or string
function pad_with_zeroes($param, $length) {
  if(is_array($param)) {
    foreach($param as $key=>$value) {
      $params[$key] = str_pad($value, $length, "0", STR_PAD_LEFT);
    }
    return $params;
  }
  else {
    return str_pad($param, $length, "0", STR_PAD_LEFT);
  }
}




// prepares string or array of strings coming from browser for inserting to database query
// trim the values too?
function in($values){
 
  if(is_array($values)){
    foreach ($values as $key => $value){
      $values[$key] = in($value);
    }
  }elseif(!is_numeric($values) && !is_null($values) && !is_bool($values)) {
    $values = mysql_real_escape_string(stripslashes(trim($values)));
  }
  
  return $values;
  
}





function make_set_clause($p){

	$ret = "";
	foreach($p as $key=>$value) {
		if(!is_null($value)) {
			$ret.="$key='$value',";
		}
		else {
			$ret.="$key=NULL,";
		}
	}
	return substr($ret, 0, -1);
}



function pair_array_data($data, $control){
	
	$myarray = array();
	
	foreach($data as $key=>$item){
		if(in_array(strval($key),$control)) $myarray[$key] = $item; 
	}
	
	return($myarray);

}


function array_remove_empty($array){
	
	$myarray = array();
	
	foreach($array as $key=>$item){
		if(!empty($item) OR is_null($item)) $myarray[$key] = $item; 
	}
	
	return($myarray);

}



/*
function options_for_select($options = array(), $selected = '', $html_options = array())
{
  if (!is_array($selected))
  {
    $selected = array($selected);
  }

  $selected = array_map('strval', array_values($selected));
  $selected_set = array_flip($selected);

  $html = '';

  if ($value = _get_option($html_options, 'include_custom'))
  {
    $html .= content_tag('option', $value, array('value' => ''))."\n";
  }
  else if (_get_option($html_options, 'include_blank'))
  {
    $html .= content_tag('option', '', array('value' => ''))."\n";
  }

  foreach ($options as $key => $value)
  {
    if (is_array($value))
    {
      $html .= content_tag('optgroup', options_for_select($value, $selected, $html_options), array('label' => $key))."\n";
    }
    else
    {
      $option_options = array('value' => $key);

      if (isset($selected_set[strval($key)])) {
        $option_options['selected'] = 'selected';
      }

      $html .= content_tag('option', $value, $option_options)."\n";
    }
  }

  return $html;
}


function select_tag($name, $option_tags = null, $options = array())
{
  $options = _convert_options($options);
  $id = $name;
  if (isset($options['multiple']) && $options['multiple'] && substr($name, -2) !== '[]')
  {
    $name .= '[]';
  }
  if (is_array($option_tags))
  {
    $option_tags = options_for_select($option_tags, $options["selected"]);
  }

  return content_tag('select', $option_tags, array_merge(array('name' => $name, 'id' => $options['id']), $options));
}

function _get_option(&$options, $name, $default = null)
{
  if (array_key_exists($name, $options))
  {
    $value = $options[$name];
    unset($options[$name]);
  }
  else
  {
    $value = $default;
  }

  return $value;
}


function _convert_options($options)
{
  foreach (array('disabled', 'readonly', 'multiple') as $attribute)
  {
    if (array_key_exists($attribute, $options))
    {
      if ($options[$attribute])
      {
        $options[$attribute] = $attribute;
      }
      else
      {
        unset($options[$attribute]);
      }
    }
  }

  return $options;
}

function content_tag($name, $content = '', $options = array())
{
  if (!$name)
  {
    return '';
  }

  return '<'.$name._tag_options($options).'>'.$content.'</'.$name.'>';
}

function _tag_options($options = array())
{
  $html = '';
  foreach ($options as $key => $value)
  {
    $html .= ' '.$key.'="'.htmlspecialchars($value).'"';
  }

  return $html;
}

*/






















function check_timeouts() {
  // check for booking timeout
  if(isset($_SESSION["booking"]["details"]["timestamp"]) && $_SESSION["booking"]["details"]["timestamp"] < time() - BOOKING_TIMEOUT) {
    // booking timeout!
    // erase booking data and inform user
    unset($_SESSION["booking"]);
    return "/hotels/booking_timeout.php";
  }

  // check for search results timeout
  if(isset($_SESSION["hotels_search_results"]["timestamp"]) && $_SESSION["hotels_search_results"]["timestamp"] < time() - SEARCH_RESULTS_TIMEOUT) {
    // search results timeout!
    // erase booking data and inform user
    unset($_SESSION["hotels_search_results"]);
    unset($_SESSION["booking"]);
    return "/hotels/search_results_timeout.php";
  }  
}







function currency_symbol($currency) {
  $symbol = $currency;
  switch($currency) {
    case 'EUR':
      $symbol = "€";
    break;
    case 'USD':
      $symbol = "$";
    break;
    default:
      $symbol = "€";
  }
  return $symbol;
}


function count_lines_in_text_file($file_location){

	$lines = 0;
	
	if ($fh = fopen($file_location, 'r')) {
	  while (!feof($fh)) {
		if (fgets($fh)) {
		  $lines++;
		}
	  }
	}
	
	return $lines;

}



function return_alt($value1,$value2,$compare,$default=1){
	$array = array('1'=>$value1, '-1'=>$value2);
	$key = array_search($compare, $array);
	$new_key = (in_array($compare,$array)) ? intval($key*(-1)) : intval($default);
	return $array[$new_key];
}



/**
 * Execute db query
 *
 * @param string $query
 * @param int $rows_num
 * @return array
 */

function apply_query($sql_query, &$num_rows = 0, $cache = false){
	// $num_rows is referenced and can be outputted outside the function
	
	$result = false;
	if($cache){
		$memcache = new Memcache;
		foreach(unserialize(CHOSTS) as $cache_server){
			$memcache->addServer($cache_server, 11211);
		}
		//create an index key for memcache
		$key = md5('query'.$sql_query);
		//lookup value in memcache
		$result = $memcache->get($key);
	}
	
	if($result){
		return $result;
	}else{
	

		switch(STAGEENV){
			case "DEV";
				$result = mysql_query($sql_query) or die (mysql_error());
			break;
			case "LIVE";
				$result = mysql_query($sql_query) or die ();
			break;
		}
		
		$num_rows = mysql_num_rows($result);
	
		if($num_rows){
			$values_array = array();
			
			/*
			for single row...
			$row = mysql_fetch_array($result, MYSQL_BOTH);
			$row = array_map('array_stripslashes', $row);
			return $row;*/
			
			while($row = mysql_fetch_array($result, MYSQL_BOTH)) {
				$data_set[] = array_map('array_stripslashes', $row);
				//$data_set[] = $row;
			}
			
			// Set cache
			if($cache) $memcache->set($key,$data_set,0,$cache['seconds']);
			
			return $data_set;
		}else{
			return false;
		}
	
	}
	
}





function align_keys($keys,$data){

	$result = array();
	$i = 0;
	foreach($keys as $key) {
		$result[$key] = $data[$i];
		$i++;
	}
	return $result;
}


function align_key2key($keys,$data){

	$result = array();
	foreach($keys as $key) {
		$result[$key] = $data[$key];
	}
	return $result;
}



function objectToArray ($object) {
	if ( count($object) > 1 ) {
		$arr = array();
		for ( $i = 0; $i < count($object); $i++ ) {
			$arr[] = get_object_vars($object[$i]);
		}
 
    	        return $arr;
 
	} else {
		return get_object_vars($object);
	}
}


function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}



function get_include_contents($filename) {
    
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $tmp = ob_get_contents();
        ob_clean();
        return $tmp;
    }
    
    return false;
}